package com.gzhryc.jdbc.utils;

import com.gzhryc.jdbc.DateBranchHelper;
import com.gzhryc.jdbc.DbHelper;
import com.gzhryc.jdbc.NumberBranchHelper;
import com.gzhryc.jdbc.annotaion.DateBranchTable;
import com.gzhryc.jdbc.annotaion.NumberBranchTable;
import com.gzhryc.jdbc.annotaion.Table;
import com.gzhryc.jdbc.annotaion.View;
import com.gzhryc.jdbc.log.Logger;
import com.gzhryc.jdbc.models.ConnectInfo;
import org.apache.commons.lang3.StringUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 初始化数据库工具
 * 
 * @author 张浩
 * @version 2016-12-7
 */
public class DbUtils {

	static Logger log = Logger.getLogger(DbUtils.class);

	public static void createDatabase(ConnectInfo info) {
		DbHelper helper = HelperUtils.createDbHelper(info.getKey());
		try {
			assert helper != null;
			if (!helper.existDb(info.getDbName())) {
				if (!helper.createDb(info.getDbName())) {
					log.error("创建数据库失败，数据连接：" + JsonTools.toJson(info));
				}
			}
		} catch (SQLException e) {
			log.error("创建数据库错误", e);
		}
	}

	public static void createTable(ConnectInfo info, String tableObjectPackage) {
		try {
			List<String> classes = PackageTools.getClassName(tableObjectPackage);
			if (classes != null && classes.size() > 0) {
				for (String str : classes) {
					Class<?> clazz = Class.forName(str);
					Table table = clazz.getAnnotation(Table.class);
					if (table != null) {
						if (!createTable(info, clazz)) {
							log.error("创建" + table.name() + "表失败，数据连接：" + JsonTools.toJson(info));
						}
						continue;
					}
				}
			}
		} catch (Exception e) {
			log.error("创建指定包中的表错误", e);
		}
	}

	public static boolean createTable(ConnectInfo info, Class<?> clazz) {
		try {
			if (clazz != null) {
				String tableName = EntityUtils.getTableName(clazz);
				if (StringUtils.isNotBlank(tableName)) {
					DateBranchTable dateBranchTable = clazz.getAnnotation(DateBranchTable.class);
					if (dateBranchTable != null) {
						String suffix = DateBranchHelper.getTableSuffix(dateBranchTable.type(), new Date());
						createTable(info, clazz, tableName + suffix);
					}
					NumberBranchTable numberBranchTable = clazz.getAnnotation(NumberBranchTable.class);
					if(numberBranchTable != null) {
						for (int i = 1; i <= 9; i++) {
							String tempTableName = tableName + "_" + i;
							createTable(info, clazz, tempTableName);
						}
					}
					//创建默认的表
					DbHelper helper = HelperUtils.createDbHelper(info.getKey());
					boolean flag = true;
					assert helper != null;
					if (!helper.existTable(info.getDbName(), tableName)) {
						if (!helper.createTable(clazz)) {
							flag = false;
						}
					}

					if (flag) {
						// 创建或修改索引
						helper.createOrUpdateIndex(tableName, clazz);
						helper.createOrUpdateUniqueKey(info.getDbName(),tableName,clazz);
					}
					return flag;
				}
			}
		} catch (Exception e) {
			log.error("创建指定类的表错误", e);
		}
		return false;
	}

	public static void createTable(ConnectInfo info, Class<?> clazz, String tableName) {
		try {
			if (clazz != null) {
				if (StringUtils.isNotBlank(tableName)) {
					DbHelper helper = HelperUtils.createDbHelper(info.getKey());
					boolean flag = true;
					assert helper != null;
					if (!helper.existTable(info.getDbName(), tableName)) {
						if (!helper.createTable(tableName, clazz)) {
							flag = false;
						}
					}

					if (flag) {
						// 创建或修改索引
						helper.createOrUpdateIndex(tableName, clazz);
						helper.createOrUpdateUniqueKey(info.getDbName(),tableName,clazz);
					}
				}
			}
		} catch (Exception e) {
			log.error("创建指定类的表(自定义表名)错误", e);
		}
	}

	public static void createView(ConnectInfo info, Class<?> clazz) {
		try {
			if (clazz != null) {
				View view = clazz.getAnnotation(View.class);
				if (view != null) {
					DateBranchTable dateBranchTable = clazz.getAnnotation(DateBranchTable.class);
					if (dateBranchTable != null) {
						String suffix = DateBranchHelper.getTableSuffix(dateBranchTable.type(), new Date());
						String viewName = view.name() + suffix;
						String asSql = view.as().replaceAll("\\{DateBranchSuffix\\}", suffix);
						createView(info, viewName, asSql);
					} else {
						String viewName = EntityUtils.getViewName(clazz);
						if (StringUtils.isNotBlank(viewName)) {
							DbHelper helper = HelperUtils.createDbHelper(info.getKey());
							assert helper != null;
							if (!helper.existView(info.getDbName(), viewName)) {
								helper.createView(clazz);
							}
						}
					}
				}
			}
		} catch (Exception e) {
			log.error("创建指定类的视图错误", e);
		}
	}

	/**
	 * 创建指定包中的视图
	 * 
	 * @param info
	 * @param tableObjectPackage
	 */
	public static void createView(ConnectInfo info, String tableObjectPackage) {
		try {
			List<String> classes = PackageTools.getClassName(tableObjectPackage);
			if (classes != null && classes.size() > 0) {
				for (String str : classes) {
					Class<?> clazz = Class.forName(str);
					createView(info, clazz);
				}
			}
		} catch (Exception e) {
			log.error("创建指定包中的视图错误", e);
		}
	}

	public static void createView(ConnectInfo info, String viewName, String asSql) {
		try {
			if (StringUtils.isNotBlank(viewName) && StringUtils.isNotBlank(asSql)) {
				DbHelper helper = HelperUtils.createDbHelper(info.getKey());
				assert helper != null;
				if (!helper.existView(info.getDbName(), viewName)) {
					helper.createView(viewName, asSql);
				}
			}
		} catch (Exception e) {
			log.error("创建指定类的视图错误", e);
		}
	}
}
